package itsm.isperp.workflow.utils;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.sequence.SequenceGenerator;
import itsm.isperp.workflow.cmd.JumpCmd;
import itsm.isperp.workflow.service.BpmProcessRunService;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import me.chanjar.weixin.common.util.StringUtils;

import org.activiti.engine.ProcessEngine;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * 
 * 
 * 
 * @author lizx
 * @date 2015-9-15
 * @since 1.0
 * 
 */
public class AutoJumpToActivityUtil {

	/**
	 * 启动流程
	 * 
	 * @param id
	 * @param startUser
	 * @throws SQLException
	 */
	public static void startProcessAndJumpTo(String id, String startUser)
			throws SQLException {
		startProcessAndJumpTo(id, startUser, null, "admin");
	}

	/**
	 * 启动流程并转派到指定人
	 * 
	 * @param id
	 *            唯一标识
	 * @param startUser
	 *            流程启动人
	 * @param assigner
	 *            分派到指定人
	 * @throws SQLException
	 */
	public static void startProcessAndAssign(String id, String startUser,
			String assigner, String suggest) throws SQLException {

		BpmProcessRunService bpmProcessRunService = ContextHolder
				.getSpringBean("bpmProcessRunService");
		// 启动流程
		bpmProcessRunService.startProcess(startUser, "incidentProcess", id,
				suggest);

		String sql = "SELECT process_id FROM icd_incident WHERE id='" + id
				+ "'";

		JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
		String process_id = null;
		process_id = jdbcTemplate.queryForObject(sql, String.class);

		// 自动分派给服务台
		bpmProcessRunService.transferAssignee(process_id, assigner, assigner,
				"转派给指定一线");

	}

	public static void getCode(String tableName, List<String> ids)
			throws SQLException {
		SequenceGenerator sg = ContextHolder.getSpringBean("sequenceGenerator");

		JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");

		// 为对于的单取号（重新设置流水号）
		for (String id : ids) {
			String sql = "UPDATE " + tableName + " SET code=? WHERE id=?";
			String seq = sg.next(tableName);
			jdbcTemplate.update(sql, seq, id);
		}
	}

	/**
	 * 启动流程，如果指定activityId跳转到此节点
	 * 
	 * @param id
	 * @param startUser
	 *            流程启动人
	 * @param activityId
	 *            目标节点
	 * @param exeUser
	 *            当前执行者
	 * @return 如果指定activityId则返回流程实例id，否则返回null
	 * @throws SQLException
	 */
	public static String startProcessAndJumpTo(String id, String startUser,
			String activityId, String exeUser) throws SQLException {

		BpmProcessRunService bpmProcessRunService = ContextHolder
				.getSpringBean("bpmProcessRunService");
		// 启动流程
		bpmProcessRunService.startProcess(startUser, "incidentProcess", id,
				"自动提交");

		String process_id = null;
		if (StringUtils.isNotEmpty(activityId)) {
			JdbcTemplate jdbcTemplate = ContextHolder
					.getSpringBean("jdbcTemplate");
			ProcessEngine processEngine = ContextHolder
					.getSpringBean("processEngine");

			String sql = "SELECT process_id FROM icd_incident WHERE id='" + id
					+ "'";

			process_id = jdbcTemplate.queryForObject(sql, String.class);

			JumpCmd cmd = new JumpCmd(process_id, activityId, exeUser,
					"自动分配");

			processEngine.getManagementService().executeCommand(cmd);
		}

		return process_id;

	}

	public static String jumpTo(List<Map<String, Object>> list)
			throws SQLException {
		String gongshi = "sid-ADA51B87-32E9-4E56-AAF2-48F417556D7E";
		String guanbi = "sid-D47177CC-4F90-41EB-A56C-50AE86EFD8A9";
		JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
		String errorIds = "";
		int i = 0;
		for (Map<String, Object> map : list) {
			String id = (String) map.get("id");
			try {

				String confirmtimeman_id = (String) map
						.get("confirmtimeman_id");
				String supporter_id = (String) map.get("supporter_id");
				String solver_id = (String) map.get("solver_id");
				String distributor_id = (String) map.get("distributor_id");
				String status = (String) map.get("status");

				// 分配到帮助台/一线 --- 分派到自己，自己还打开 -----------分派人
				// -------------------------------
				// 帮助台/一线处理中 --- 一线拍给自己， -support_id，待回访 --一线，并且已经打开

				// IS审核中 --- 需求单，资质单在担当审核（单据在一线手上）
				// 审批已完成 ---

				// 已解决 --- 工程师已经处理完成，担当还没打开 --confirmtimeman_id （工时审核）
				// 工时待确认 --- 担当打开后 --confirmtimeman_id （工时审核）

				// 工时已确认 --- 担当确认了工时 --分派人（关闭）

				// 二线处理中-IS部 --- 二线工程师为IS担当 --supporter_id（二线处理）
				// 二线处理中-outside --- -supporter_id（二线处理）
				// 二线处理中-inside --- -supporter_id（二线处理）
				// 分配到三线 --- 二线在做操作 --supporter_id（二线处理）
				// 三线处理中 --- 二线在做操作 --supporter_id（二线处理）
				// 二线分析中 --- 在二线处理环节 --supporter_id（二线处理）

				// 分配到二线-inside --- -supporter_id（二线受理）
				// 分配到二线-outside --- -supporter_id（二线受理）

				switch (status) {
				case "分配到帮助台/一线":
				case "帮助台/一线处理中":
					// 如果有solver_id则派到带关闭环节，处理人为distributor_id
					// 否则，如果有supporter_id， 那么调度到二线处理 ，处理人 就用supporter_id
					// 否则，处于初始状态（共享模式）
					if (StringUtils.isNotEmpty(solver_id)) {
						startProcessAndJumpTo(id, distributor_id, guanbi,
								distributor_id);
					} else if (StringUtils.isNotEmpty(supporter_id)) {
						jdbcTemplate
								.update("UPDATE icd_incident SET solution_stage='一线解决' , deal_type='2' WHERE id='"
										+ id + "'");
						startProcessAndJumpTo(id, distributor_id);
					} else {
						// 此步骤需要转派
						jdbcTemplate
								.update("UPDATE icd_incident SET deal_type=NULL WHERE id='"
										+ id + "'");
						startProcessAndAssign(id, distributor_id,
								distributor_id, "自动发起");
					}

					break;
				case "二线处理":
				case "二线处理中-IS部":
				case "二线处理中-outside":
				case "二线处理中-inside":
				case "分配到三线":
				case "三线处理中":
				case "二线分析中":
				case "分配到二线-inside":
				case "分配到二线-outside":
					jdbcTemplate
							.update("UPDATE icd_incident SET deal_type='2' WHERE id='"
									+ id + "'");
					startProcessAndJumpTo(id, distributor_id);

					break;

				case "IS部审批中":
				case "审批已完成":
					jdbcTemplate
							.update("UPDATE icd_incident SET deal_type=NULL WHERE id='"
									+ id + "'");
					startProcessAndJumpTo(id, distributor_id);

					break;
				case "已解决":
				case "工时待确认":

					jdbcTemplate
							.update("UPDATE icd_incident SET deal_type='2' WHERE id='"
									+ id + "'");

					startProcessAndJumpTo(id, distributor_id, gongshi,
							confirmtimeman_id);
					break;

				case "工时已确认":
					jdbcTemplate
							.update("UPDATE icd_incident SET deal_type='2' WHERE id='"
									+ id + "'");
					startProcessAndJumpTo(id, distributor_id, guanbi,
							distributor_id);

					break;

				default:// 其它的就只启动流程
					// startProcessAndJumpTo(id, distributor_id);
					break;
				}
				i++;
			} catch (Exception e) {
				errorIds += "," + id;
			}
		}
		return i + "-" + errorIds;
	}

	public static void jumpTo() throws SQLException {

		JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");

		// 根据状态跳转
		String sql = "SELECT id,confirmtimeman_id,supporter_id,solver_id，distributor_id,status "
				+ " FROM icd_incident "
				+ " WHERE  STATUS<>'已关闭'  AND process_id IS NULL ";

		List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
		jumpTo(list);
	}
}
